<?php 
// +----------------------------------------------------------------------
// | CRMUU-企微SCRM是专业的企业微信第三方源码系统.
// +----------------------------------------------------------------------
// | [CRMUU] Copyright (c) 2022 http://crmuu.com All rights reserved.
// +----------------------------------------------------------------------

namespace app\wework\model;
use think\facade\Db;
use think\facade\Session;

/**
*回调model层
**/
class CallbackModel {

	/**
	*	获取企业配置，wid
	*	@param $corp_id 企业corp_id 
	*/
	static public function getConfig($corp_id){
		$where["corp_id"] = $corp_id;
		$res = Db::table("kt_wework_config")->where($where)->find();
		return $res;
	}

	/**
	*	获取员工信息
	*	@param $userid 员工userid
	*/
	static public function getUser($wid,$userid){
		$where["wid"] = $wid;
		$where["userid"] = $userid;
		$res = Db::table("kt_wework_staff")->where($where)->find();
		return $res;
	}

	/**
	*	获取客户信息
	*	@param $staff_id 员工id
	*	@param $external_userid 客户external_userid
	*/
	static public function getCustomer($wid,$staff_id,$external_userid){
		$where["wid"] = $wid;
		$where["staff_id"] = $staff_id;
		$where["external_userid"] = $external_userid;
		$res = Db::table("kt_wework_customer")->where($where)->find();
		return $res;
	}

	/**
	*	添加修改状态信息
	*	@param $staff_id 员工id
	*	@param $external_userid 客户external_userid
	*/
	static public function customerSave($id,$status){
		$where["id"] = $id;
		$arr["del_time"] = time();
		$arr["status"] = $status;
		$res = Db::table("kt_wework_customer")->where($where)->save($arr);
		return $res;
	}

	/**
	*	客户动态存储
	*	@param $wid
	*	@param $type 类型
	*	@param $arr 客户信息
	*/
	static public function dynamicSave($wid,$type,$arr){
		$where = array();
		$data["wid"] = $wid;
		$data["create_time"] = date("Y-m-d H:i:s",time());
		$data["update_time"] = date("Y-m-d H:i:s",time());
		$data["type"] = $type;
		$data["customer_userid"] = $arr["ExternalUserID"];
		if($type == 4) $data["chat_id"] = $arr["ChatId"];
		if($type != 4) $data["staff_id"] = self::getUser($wid,$arr["UserID"])["id"];
		$res = Db::table("kt_wework_customer_dynamic")->where($where)->save($data);
		return $res;
	}

	/**
	*	删除流失
	*	@param $wid
	*	@param $type 类型
	*	@param $arr 客户信息
	*/
	static public function lossingSave($data){
		$res = Db::table("kt_wework_customer_dynamic")->insertGetId($data);
		return $res;
	}
	

	static public function lossing($data){
		$res = Db::table("kt_wework_customer_lossing")->insertGetId($data);

		return $res;
	}

	/**
	*	指定时间到现在的天数
	*	@param $start_ts 开始时间
	*	@param $end_ts 结束时间
	*/
	static public function dateDay($start_ts){
		$end_ts = time();
		$diff = $end_ts - $start_ts; 
		$n = round($diff / 86400);
		return $n;
	}

}